<template>
<view class="form-wrap"> 
	<view class="form-upload-item">
		<view class="hd">			
			<view class="title a-t">
				<text class="iconfont">&#xe62f;上传附件</text>
				<text class="f-s24 f-grey">(只支持.pdf、.doc/.docx、.xls/.xlsx)</text>
			</view>
			<view class="iconfont f-s48" @click="showPopup('show','isChoseFile')">&#xe635;</view> 
		</view>
		<!-- <template v-if="loadingState.default">
			<c-loading :loadingState="loadingState"></c-loading>
		</template> -->
		<template>
			<view v-if="files.length>0" class="file-list">
				<view class="file-item" v-for="(item,index) in files" :key="index">
					<view class="left">
						<view class="icon">
							<image v-if="$checkFileType(item.file_name)==3" src="@/static/images/pdf.png" mode="widthFix"></image>
							<image v-if="$checkFileType(item.file_name)==1" src="@/static/images/word.png" mode="widthFix"></image>
							<image v-if="$checkFileType(item.file_name)==2" src="@/static/images/excel.png" mode="widthFix"></image>
							<image v-if="$checkFileType(item.file_name)==4" src="@/static/images/image.png" mode="widthFix"></image> 
							<image v-if="$checkFileType(item.file_name)==5" src="@/static/images/txt_icon.png" mode="widthFix"></image>
						</view>
						<view class="name-area">	
							<view class="name split">{{item.file_name}}</view>
							<view class="size">{{item.create_time}}</view>
						</view>
					</view>
					<!-- 项目经理 总经办29 报告撰写组 超级管理员-->
					<template v-if="userInfo.dep_leader==1
						||userInfo.department_id==29 ||userInfo.department_id==10    // 总经办 报告撰写
						||userInfo.role_id==1   // 超级管理员
						||userInfo.id==item.user_id || userInfo.id==pro_detail.director || userInfo.id==pro_detail.responsible"  >
						<view class="handle-btn">
							<view class="icon iconfont f-blue f-s46" @click="showHandle(index)">&#xe8c4;</view> 
						</view>
						<!-- <view class="iconfont del-icon f-s36" @click="del(index)">&#xe8b6;</view> -->
					</template>
				</view> 
			</view>
		</template>
	</view> 
	 
	
	
	<view v-if="flag.isFullPage" class="full-fix-page">
		<view v-if="flag.isChoseFile" class="chosefiles-area a-fadeinB">
			<view class="file-type-list">
				<!-- <view class="item" @click="uploadImage(1)">
					<view class="icon iconfont f-s44">&#xe7be;</view>
					<view class="name">相册</view>
				</view>
				<view class="item" @click="uploadImage(2)">
					<view class="icon iconfont f-s44">&#xe8c7;</view>
					<view class="name">拍摄</view>
				</view> -->
				<view class="item" @click="openFiles">
					<view class="icon iconfont f-s42">&#xeac5;</view>
					<view class="name">文件</view>
				</view> 
			</view>
			<view class="bottom-lay-btn-wrap" @click="showPopup('hide','isChoseFile')">
				<view class="lay-btn">取消</view> 
			</view> 
		</view>
		
		<!-- 上传文件 --> 
		<view v-if="flag.isUploadFile" class="popup-wrap a-fadein">
			<view class="popup-type-model">
				<view class="close-btn iconfont f-s44" @click="showPopup('hide')">&#xeb6a;</view>
				<view class="popup-body">
					<view class="title">上传文件</view>
					<view class="content upload-remark">
						<view class="inp-bar">
							<textarea class="text" v-model="remark" placeholder="文件说明"></textarea> 
						</view>						
						<view class="comfirm-btn" @click="showPopup('show','isChoseFile')">选择文件</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 修改文件名 -->
		<view v-if="flag.isChangeName" class="popup-wrap a-fadein">
			<view class="popup-type-model">
				<view class="close-btn iconfont f-s44" @click="showPopup('hide')">&#xeb6a;</view>
				<view class="popup-body">
					<view class="title">文件重命名</view>
					<view class="content reset-name">
						<view class="inp-bar">
							<input type="text" v-model="file_name" class="text" placeholder="输入新名称">
							<view v-if="file_name" class="iconfont" @click="clearName">&#xe724;</view>
						</view>						
						<view class="comfirm-btn" @click="updateName">确定</view>
					</view>
				</view>
			</view>
		</view>
		
		<view v-if="flag.isShowHandle" class="bottom-tab-btn a-fadeinB">
			<template>
				<view class="bottom-lay-btn-wrap m-b2">					
					<view  class="lay-btn" @click="previewPic">预览</view> 
					<view class="lay-btn" @click="resetName">重命名</view> 
					<view  class="lay-btn" @click="checkFileStorage">下载</view>
					<view class="lay-btn f-red" @click="del">删除</view> 
				</view>
				<view class="bottom-lay-btn-wrap m-b2">
					<view class="lay-btn" @click="showPopup('hide')">取消</view> 
				</view> 
			</template>
			
			
			
		</view>
		
	</view>
</view>
</template>

<script>
import {uploadImage,uploadToServe,checkFileType,previewImage} from '@/common/util.js'  
import { HOST } from '../config.js'
export default{
	name:'loading',
	data(){
		return {
			userInfo:uni.getStorageSync('userInfo'),
			flag:{		// 弹窗相关
				isFullPage:false,  
				isChoseFile:false,
				isChangeName:false,
				isUploadFile:false,
				isShowHandle:false
			}, 
			isShowHandle:false,
			select_files:{},
			files:[], 
			file_name:'',
			remark:'',
			idx:'',
			id:'',
			isStop:true,
			loadingState:{
				default:true
			},
			pro_detail:{}, 
		}
	},
	props:{
		 
	},
	created() {    
		console.log(this.module,this.procure_id)
		if(this.module=='caigou'){
			 
		}else{
			if(this.pro_id){
				this.userInfo=uni.getStorageSync('userInfo'); 
				 
			}	
		}
			
	},
	methods:{ 
		// 项目详情
		async getDetail() {
			let res = await this.$api.user_api.projectInfo({
				id: this.pro_id
			})     
			console.log(213123,this.task_id,this.type,res)
			if (res.data.code == 200) {
				this.loadingState.default=false;
				this.pro_detail=res.data.data;  
				res.data.data.files.forEach(item=>{ 
					if(this.type==item.type){
						if((this.type==6||this.type==5) && this.task_id==item.task_id){
							this.files.push(item);	
						} 	
						 
						
						if(this.type!=6||this.type!=5){
							this.files.push(item);
						}
					} 
				})  
			}
		},
		
		// 打开弹窗
		showPopup(t, n) { 
			if (t == 'show') {
				this.flag.isFullPage = true;
				this.flag[n] = true;
			} else if (t == 'hide') {
				for (let i in this.flag) {
					if(n){
						this.flag[n] = false;
					}else{
						this.flag[i] = false;
					}					
				}
			}
		},
		
		// 打开操作按钮
		async showHandle(idx){	 
			this.showPopup('show','isShowHandle'); 			
			this.idx=idx;  
			console.log(123123,this.files[idx])
		},
		
		async procurefileshowfiles(){
			let res=await this.$api.user_api.procurefileshowfiles({
				procure_id:this.procure_id,
				type:this.type,
				filename:'',
				remark:'',
				id:'',
				user_id:'',
			})  
			if(res.data.code==200){
				this.loadingState.default=false;
				this.files=res.data.data;  				 
			}
		},
		
		resetName(){ 
			this.showPopup('hide');
			this.showPopup('show','isChangeName'); 
			let name_arr=this.files[this.idx].file_name.split('.');
			name_arr.length=name_arr.length-1; 			
			this.file_name=name_arr.join(''); 
			this.id=this.files[this.idx].id;
		},
		
		clearName(){
			this.file_name='';
		},
		
		// 重命名文件
		async updateName(){ 
			if(this.file_name==''){
				this.$showToast({
					title:'请输入文件名'
				})
				return
			}
			
			if(this.isStop){
				this.isStop=false;
				let res={};
				if(this.module=='caigou'){
					res=await this.$api.user_api.procurefilerename({
						id:this.id,
						name:this.file_name
					})
				}else{
					res=await this.$api.user_api.filesResetName({
						id:this.id,
						name:this.file_name
					}) 
				}  
				if(res.data.code==200){
					this.$showToast({
						icon:'success',
						title:'重命名成功'
					})
					this.showPopup('hide');  
					this.isStop=true;					 
					this.files.splice(this.idx,1,res.data.pdata) 
				}else{
					this.$showToast({
						icon:'error',
						title:res.data.msg
					})
					this.isStop=true;
				}
				
			}
			
		},
		
		// 预览文件
		previewPic(){
			console.log()
			this.showPopup('hide');  
			if(this.$checkFileType(this.files[this.idx].file_name)==4){	
				let path="";
				if(this.module=='caigou'){
					path=`${HOST}/api/image/image?procure_id=${this.procure_id}&user_id=${this.files[this.idx].user_id}&type=${this.type}&img=${this.files[this.idx].file_name}`; 
				}else{
					path=`${HOST}/api/image/image?task_id=${this.files[this.idx].task_id}&project_id=${this.pro_id}&img=${this.files[this.idx].file_name}`;
				}	 
				console.log(123,path)
				previewImage({
					data:[path],
					index:0,
				})
			}else if(this.$checkFileType(this.files[this.idx].file_name)==5){
				 
				 
			}else{		 
				uni.navigateTo({
					url:`/pages/webview/webview?module=hetong&type=${this.files[this.idx].type}&procure_id=${this.procure_id}&name=${this.files[this.idx].file_name}&user_id=${this.files[this.idx].user_id}`
				})		 
			}  
		},
		
		// 删除文件
		del(){
			let _this=this; 
			uni.showModal({ 
				content:'文件删除后将不可在找回，确定删除该文件吗？',
				mask:true,
				async success(res) {
					if(res.confirm){
						let del_res={};
						if(_this.module=='caigou'){
							del_res=await _this.$api.user_api.procurefiledelfile({
								id:_this.files[_this.idx].id
							})
						}else{
							del_res=await _this.$api.user_api.delFiles({
								id:_this.files[_this.idx].id
							})
						}						 
						if(del_res.data.code==200){
							_this.$showToast({
								icon:'success',
								title:'文件删除成功'
							})
							_this.showPopup('hide');
							_this.isStop=true;		
							_this.files.splice(_this.idx,1)
						}
					}
				}
			})
		},
		
		// 获取本地文件
		openFiles(){
			const plugin = uni.requireNativePlugin('GuoWei-SelectFileModule'); 
			let _this=this;
			let api_url='/api/product/uploadfile';
			let params={}; 
			params={
				apply_type:10  
			}
			this.showPopup('hide'); 
			plugin.chooseFile(
			    {
			        count: 1,
			        extension: [],
			        rootDirName: '我的文件',
			        themeColor: '#00ff00',
			        folderIconColor: '#00ff00',
			        fileIconColor: '#0000ff',
			        showHiddenFiles: false
			    }, 
			    result => {   
					uploadToServe({
						url: api_url,
						filePath: result.files[0].path,
						name: 'fileinput',
						formData: params
					}).then(async (up_res) => {  
						if(up_res.code==200){
							_this.files=_this.files.concat(up_res.data);  
							_this.$store.commit('hetong',_this.files);
						}else{
							uni.showModal({
								content:up_res.msg,
								mask:true,
								showCancel:false,
								confirmText:'重新上传'
							})
						}	 						
					}).catch((err)=>{ 
					})
			    }
			)
		},
		
		// 上传图片
		uploadImage(type) { 
			let _this = this;
			let api_url=''; 
			let params={};
			// type 1 相册上传  2 照相机
			// 上传现场照片
			
			this.showPopup('hide'); 
			let sourceType=[];
			if(type==1){
				sourceType=['album']
			}else {
				sourceType=['camera']
			}
			
			if(this.module=='caigou'){				
				api_url='/api/procurefile/uploadfile';
				params={
					'procure_id': _this.procure_id,
					'type': _this.type,      //  1=合同,2=发票,3=图片,4=采购计划,5,货款核销9=其他
					'fileinput': _this.task_id,
					'remark':_this.remark
				} 
			}else{				
				api_url='/api/file/uploadfile';
				params={  
					'project_id': _this.pro_id,
					'type': _this.type,     //  1 合同 2 标书 3 图片 4 其他 5 财务 6 业务 7 验收报告
					'task_id': _this.task_id,
					'remark':_this.remark
				} 
			} 
			uploadImage({
				length: _this.files.length,
				maxSize: 9,
				sourceType:sourceType,
				async success(res) {   
					let upload_num=0; 
					res.tempFilePaths.forEach(item=>{ 
						uploadToServe({
							url: api_url,
							filePath: item,
							name: 'fileinput',
							formData: params
						}).then(async up_res=>{		 
							if(up_res.code==200){
								upload_num+=1;
								_this.files=_this.files.concat(up_res.data); 
								
								if(_this.module=='caigou'){
									_this.$store.commit('CAIGOU_LIST_UPDATE',1); 	 
								}else{ 
									if(res.tempFilePaths.length===upload_num){
										
										if(_this.type==2){
											// 标书上传成功  通知项目经理 审批人   
											let res=await _this.$api.user_api.addMsg({
												project_id:_this.pro_id, 
												task_id:'',
												content:`【${_this.userInfo.username}】上传了《${_this.pro_detail.project_name}》项目的标书文件，请知悉！`,
												user_id:[19,_this.pro_detail.approver,_this.pro_detail.responsible].join('_'),
												type:1,
												content_type:4,  // 通知消息 
												title:`《${_this.pro_detail.project_name}》项目标书上传的通知`,
											}); 								
										}
										
										if(_this.type==5){
											// 财务上传成功  通知项目经理 审批人  
											let res=await _this.$api.user_api.addMsg({
												project_id:_this.pro_id, 
												task_id:'',
												content:`【${_this.userInfo.username}】上传了《${_this.pro_detail.project_name}》项目回款的发票/回执文件，请知悉！`,
												user_id:[19,_this.pro_detail.approver,_this.pro_detail.responsible].join('_'),
												type:1,
												content_type:2,   // 项目回款 
												title:`《${_this.pro_detail.project_name}》项目回款的通知`,
											});  
											_this.$store.commit('PROJECT_LIST_UPDATE',1);
										}
										
										if(_this.type==7){
											console.log(123123123123)
											// 验收材料上传成功  通知项目经理 审批人 
											let res=await _this.$api.user_api.addMsg({
												project_id:_this.pro_id, 
												task_id:'',
												content:`【${_this.userInfo.username}】上传了《${_this.pro_detail.project_name}》项目的验收材料文件，请知悉！`,
												user_id:[19,_this.pro_detail.approver,_this.pro_detail.responsible].join('_'),
												type:1,
												content_type:4,
												title:`《${_this.pro_detail.project_name}》项目验收材料文件上传的通知`,
											}); 
											let update_status = await _this.$api.project_api.updateProjectStatus({
												id:_this.pro_detail.id,
												status: '5',
												content: _this.pro_detail.responsible_name+'项目验收中',
											})
											_this.$store.commit('PROJECT_LIST_UPDATE',1); 
										}	
										
										if(_this.type==10){
											console.log(12312312312345)
											// 验收意见上传成功  通知项目经理 审批人 
											let res=await _this.$api.user_api.addMsg({
												project_id:_this.pro_id, 
												task_id:'',
												content:`【${_this.userInfo.username}】上传了《${_this.pro_detail.project_name}》项目的验收意见文件，请知悉！`,
												user_id:[19,_this.pro_detail.approver,_this.pro_detail.responsible].join('_'),
												type:1,
												content_type:4,
												title:`《${_this.pro_detail.project_name}》项目验收意见文件上传的通知`,
											}); 
											// let update_status = await _this.$api.project_api.updateProjectStatus({
											// 	id:_this.pro_detail.id,
											// 	status: '5',
											// 	content: _this.pro_detail.responsible_name+'项目验收中',
											// })
											_this.$store.commit('PROJECT_LIST_UPDATE',1);
										}		 
									}
								}
								
							}else{
								_this.$showToast({
									icon:'error',
									title:up_res.msg,
								})
							}						
						})
					})  
					 
				}
			})
		},
		
		// 检测文件存储是否开启
		checkFileStorage(){
			let _this = this;
			plus.android.requestPermissions(['android.permission.WRITE_EXTERNAL_STORAGE'], function(e) {  
				// 权限被永久拒绝
				if (e.deniedAlways.length > 0) { 
					// 弹出提示框解释为何需要读写手机储存权限，引导用户打开设置页面开启
					uni.showModal({
						title: '存储权限',
						content: '您拒绝了存储权限，请去设置-应用开启存储权限。',
						success: function (res) {
							if (res.confirm) {
								// console.log('用户点击确定');
							} else if (res.cancel) {
								// console.log('用户点击取消');
							}
						}
					});
				}
				
				// 权限被临时拒绝
				if (e.deniedPresent.length > 0) { 
					// 弹出提示框解释为何需要读写手机储存权限，可再次调用plus.android.requestPermissions申请权限
					plus.android.requestPermissions(['android.permission.WRITE_EXTERNAL_STORAGE'])
					// console.log('666666666 ' + e.deniedPresent.toString());
				}
				
				// 权限已打开
				if (e.granted.length > 0) { 
					console.log('可以下载')  
					_this.downLoad();
				}
			}, function(e) {
				// console.log('R12133313221' + JSON.stringify(e));
			}); 
		},
		
		// 下载文件
		downLoad(){				
			this.showPopup('hide');
			let path='';
			if(this.module=='caigou'){
				path=`${HOST}/api/procurefile/downloadfile?procure_id=${this.procure_id}&user_id=${this.send_user}&type=${this.type}` 
			}else{
				path=`${HOST}/api/file/viewfile?task_id=${this.files[this.idx].task_id}&project_id=${this.files[this.idx].project_id}&name=${this.files[this.idx].file_name}`
			} 
			uni.showLoading({
				title: "下载中...",
				mask:true
			})  
			let dtask = plus.downloader.createDownload(path, {
				filename: "file://storage/emulated/0/瑞丰生物/" + this.files[this.idx].file_name       //利用保存路径，实现下载文件的重命名
			},(d, status)=> {
				//d为下载的文件对象 
				if (status == 200) {
					uni.hideLoading();
					uni.showToast({
						icon: 'none',
						mask: true,
						title: '文件已保存', //保存路径
						duration: 3000,
					});
					//下载成功,d.filename是文件在保存在本地的相对路径，使用下面的API可转为平台绝对路径
					let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename); 
				} else {
					//下载失败
					uni.hideLoading();
					plus.downloader.clear(); //清除下载任务
					uni.showToast({
						icon:'none',
						mask:true,
						title: '下载失败，请稍后重试',
					});
				}
			})
			dtask.start(); 		 
			
		},
		
	 
	
	},
	
	watch:{ 
	} 
}
</script>

<style lang="less" scoped>
	.form-upload-item{
		.label{
			margin: 20rpx;
			color:#666;
		}
		.hd{
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding-right: 20rpx;			
			.title{
				margin: 20rpx;
				color: #333;
			}
			.iconfont{
				color:#999;
			}
		}
		.file-list{
			padding: 20rpx;
			background: #fff;
		}
	}    
	.file-list{
		.file-item{
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding:20rpx;
			margin-bottom: 10rpx;
			background: #f5f5f5;
			border-radius: 10rpx;
			.left{
				display: flex;
				max-width: 90%;
			}
			.icon{
				flex-shrink: 0;
				width: 50rpx;
				margin-right: 30rpx;
			}
			.name-area{
				flex-grow: 2; 
				max-width: 90%;
				margin-right: 20rpx;
				.name{ 
					font-size: 30rpx; 
				}
				.size{
					font-size: 26rpx;
					color:#999; 
				}
			}
			.del-icon{
				color:#666;
			}
			.handle-btn{
				flex-shrink: 0;
				position: relative;
				width: 40rpx;
				height: 50rpx; 
				.icon{
					line-height: 50rpx;
				}
				.files-handle-btn-wrap{
					position: absolute;
					right:0;
					top:40rpx;
					z-index: 100;
					width: 150rpx; 
					background: #fff;
					border-radius: 10rpx;
					border: 1rpx solid #eee;
					.btn{
						padding:8rpx 20rpx;
						border-bottom:1rpx solid #eee;
						font-size: 24rpx;
						color:#666;
					}
				}
			}
		}
	}      
	  
	.reset-name{
		.inp-bar{
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 80rpx; 
			margin-bottom: 30rpx;
			border: 1rpx solid #eee;
			border-radius: 10rpx;			
			.text{
				padding:0 10px;
				flex-grow: 2;
				font-size: 28rpx;
			}
			.iconfont{
				width: 40rpx;
				flex-shrink: 0;
				color:#f00;
			}
		}
		
	}
	.upload-remark{
		.inp-bar{
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 100rpx; 
			margin-bottom: 30rpx;
			border: 1rpx solid #eee;
			border-radius: 10rpx;					
			.text{
				width: 96%;
				height: 96%;
				padding:2%;
				flex-grow: 2;
				font-size: 28rpx; 
			} 
		}
		
	}
	.comfirm-btn {
		height: 70rpx;
		line-height: 70rpx;
		margin: 0 auto;
		background: #09f;
		border-radius: 8rpx;
		color: #fff;
		text-align: center;
		font-size: 30rpx;
	}
</style>
